<template>
  <div :class="[prefixCls, { fullscreen }]">
    <Upload
      name="file"
      :multiple="maxCount > 0x1 ? true : false"
      @change="handleChange"
      :action="uploadFileUrl"
      :showUploadList="false"
      :accept="accept"
      :max-count="maxCount"
    >
      <!-- 富文本编辑器上方的图片上传 -->
      <a-button type="primary" v-bind="{ ...getButtonProps }">
        <!-- {{ t('component.upload.imgUpload') }} -->
        上传图片/视频
      </a-button>
    </Upload>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, inject } from 'vue';

  import { Upload } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useGlobSetting } from '/@/hooks/setting';
  import { uploadFileApi } from '/@/api/platform/file';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FILE_UPLOAD_PROPS_KEY, FILE_UPLOAD_FILES_KEY } from '/@/enums/provideEnum';

  export default defineComponent({
    name: 'TinymceImageUpload',
    components: { Upload },
    props: {
      fullscreen: {
        type: Boolean,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['uploading', 'done', 'error'],
    setup(props, { emit }) {
      console.log('src\\components\\Tinymce\\src\\ImgUpload.vue props', props);
      //允许上传的文件类型，默认为允许上传图片和视频，从父组件传值中获取（如果有）
      const accept = ref<string>('.jpg,.jpeg,.gif,.png');
      const maxCount = ref<number>(1);
      const provideFileUploadProps = inject(FILE_UPLOAD_PROPS_KEY);
      console.log('provideFileUploadProps', provideFileUploadProps);
      if (provideFileUploadProps != undefined && provideFileUploadProps != null) {
        accept.value = provideFileUploadProps.accept;
        maxCount.value = provideFileUploadProps.maxCount;
      }

      let uploading = false;

      const { uploadUrl } = useGlobSetting();
      const uploadFileUrl = uploadUrl + uploadFileApi;
      const { t } = useI18n();
      const { prefixCls } = useDesign('tinymce-img-upload');

      const { createMessage } = useMessage();

      const getButtonProps = computed(() => {
        const { disabled } = props;
        return {
          disabled,
        };
      });

      function handleChange(info: Recordable) {
        // console.log('handleChange info', info);
        // console.log('handleChange info.file', info.file);
        // console.log('handleChange info.file.response', info.file.response);
        const file = info.file;
        const status = file?.status;
        //渠成上传文件接口后台没有返回url，获取返回的文件id
        // const url = file?.response?.url;
        const fileid = file?.response?.data?.fileid;
        const name = file?.name;
        const type = file?.type;

        if (status === 'uploading') {
          if (!uploading) {
            emit('uploading', name);
            uploading = true;
          }
        } else if (status === 'done') {
          //还需要根据渠成上传文件后台反馈的状态和信息进行判断
          if (!file.response) {
            //后台接口响应信息为空
            createMessage.error('文件上传失败，后台无处理响应结果。');
            emit('error');
            uploading = false;
          } else {
            if (file.response.code === 0) {
              //如果msg为空表示正确，msg不为空表示错误提示信息
              if (!file.response.msg) {
                //判断data中的结果，根据data中的success判断是否成功
                if (!file.response.data) {
                  createMessage.error('文件上传失败，后台响应结果中无任何数据。');
                  emit('error');
                  uploading = false;
                } else {
                  if (file.response.data.success === true) {
                    emit('done', name, fileid, type);
                    uploading = false;
                  } else {
                    createMessage.error(file.response.data.msg);
                    emit('error');
                    uploading = false;
                  }
                }
              } else {
                createMessage.error(file.response.msg);
                emit('error');
                uploading = false;
              }
            } else {
              //code不为0表示错误
              createMessage.error(
                '文件上传失败，后台处理代码为：' +
                  file.response.code +
                  '，后台提示信息为：' +
                  file.response.msg,
              );
              emit('error');
              uploading = false;
            }
          }
        } else if (status === 'error') {
          //根据file.response信息判断错误提示
          let errorMessageContent = '文件上传失败';
          if (info.file.response.code === 0) {
            //请求完成，返回错误提示信息
            errorMessageContent = '文件上传失败，' + file?.response?.data.data.msg;
          } else {
            //请求错误
            errorMessageContent = '文件上传失败，' + file?.response?.error;
          }
          createMessage.error(errorMessageContent);
          emit('error');
          uploading = false;
        }
      }

      return {
        accept,
        maxCount,
        prefixCls,
        handleChange,
        uploadFileUrl,
        t,
        getButtonProps,
      };
    },
  });
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-tinymce-img-upload';

  .@{prefix-cls} {
    position: absolute;
    top: 4px;
    right: 10px;
    z-index: 20;

    &.fullscreen {
      position: fixed;
      z-index: 10000;
    }
  }
</style>
